package com.uobgroup.ews.uam.web.validation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.uobgroup.ews.uam.core.domain.SecurityGroup;
import com.uobgroup.ews.uam.core.service.SecurityGroupService;

@Component
public class SecurityGroupValidator implements Validator {

   @Autowired
   private SecurityGroupService securityGroupService;

   @Autowired
   private ReloadableResourceBundleMessageSource messageSource;

   @Override
   public boolean supports(Class<?> clazz) {
      return SecurityGroup.class.getName().equals(clazz.getName());
   }

   @Override
   public void validate(Object target, Errors errors) {
      SecurityGroup securityGroup = (SecurityGroup) target;
      Long securityGroupId = securityGroup.getId();
      if (securityGroupId == null || securityGroupId.longValue() == 0) {
         if (securityGroupService.hasSecurityGroup(securityGroup.getDisplayName())) {
            errors.rejectValue("displayName", "filed_unique", new String[] { securityGroup.getDisplayName() }, null);
         }
      }
      else {

         SecurityGroup existed = this.securityGroupService.findSecurityGroup(securityGroupId);
         if (isUsedByAnotherResources(existed)) {
            errors.rejectValue("displayName", "field_cannot_update", new String[] { "'" + existed.getDisplayName()
                  + "'" }, null);
         }

         if (!errors.hasFieldErrors("displayName")
               && !(existed.getDisplayName().equals(securityGroup.getDisplayName()))) {
            if (securityGroupService.hasSecurityGroup(securityGroup.getDisplayName())) {
               errors.rejectValue("displayName", "filed_unique", new String[] { securityGroup.getDisplayName() }, null);
            }
         }
      }
   }

   public boolean validateDelete(Object target, Model uiModel) {
      SecurityGroup existed = (SecurityGroup) target;
      if (isUsedByAnotherResources(existed)) {
         uiModel.addAttribute("messageError", messageSource.getMessage("field_cannot_update", new String[] { "'"
               + existed.getDisplayName() + "'" }, "", null));
         return false;
      }
      return true;
   }

   private boolean isUsedByAnotherResources(SecurityGroup securityGroup) {
      if (securityGroup.getAccessToStaff() != null || securityGroup.getProfile() != null
            || securityGroup.getSegment() != null || securityGroup.getUamRole() != null) {
         return true;
      }
      return false;
   }
}
